package com.sky.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sky.constant.RedisConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.SetmealDTO;
import com.sky.dto.SetmealPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.entity.Setmeal;
import com.sky.entity.SetmealDish;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetmealDishMapper;
import com.sky.mapper.SetmealMapper;
import com.sky.result.PageResult;
import com.sky.service.ISetmealService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sky.vo.DishItemVO;
import com.sky.vo.SetmealVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 套餐 服务实现类
 * </p>
 *
 * @author chensheng
 * @since 2025-08-08
 */
@Slf4j
@Service
public class SetmealServiceImpl extends ServiceImpl<SetmealMapper, Setmeal> implements ISetmealService {

    @Autowired
    private SetmealMapper setmealMapper;

    @Autowired
    private SetmealDishMapper setmealDishMapper;
    @Autowired
    private DishMapper dishMapper;

    @Autowired
    private RedisTemplate redisTemplate;


    /**
     * 套餐分页查询
     *
     * @param sDTO
     * @return
     */
    @Override
    public PageResult pageQuery(SetmealPageQueryDTO sDTO) {
        Page<SetmealVO> page = new Page<>(sDTO.getPage(),sDTO.getPageSize());
        setmealMapper.selectByCondition(page,sDTO);
        return PageResult.builder()
                .total(page.getTotal())
                .records(page.getRecords())
                .build();
    }

    /**
     * 新增套餐
     *
     * @param sDTO
     */
    @Override
    public void addSetmeal(SetmealDTO sDTO) {
        //新增套餐数据
        Setmeal setmeal = new Setmeal();
        BeanUtils.copyProperties(sDTO,setmeal);
        setmealMapper.insert(setmeal);

        //新增套餐菜品关联数据
        List<SetmealDish> setmealDishes = sDTO.getSetmealDishes();
        setmealDishes.forEach(setmealDish -> setmealDish.setSetmealId(setmeal.getId()));
        setmealDishMapper.insert(setmealDishes);
    }

    @Override
    public void deleteByIds(List<Long> ids) {
        //1.查询套餐状态，判断是否可以删除
        List<Setmeal> setmealList = setmealMapper.selectByIds(ids);
        //在售的套餐不能删除
        for (Setmeal setmeal : setmealList) {
            if (setmeal.getStatus().equals(StatusConstant.ENABLE)) {
                throw new DeletionNotAllowedException("起售中的套餐不能删除");
            }
        }
        setmealMapper.deleteByIds(ids);

    }

    /**
     * 套餐启售停售
     */
    @Override
    public void startOrStop(Integer status, Long id) {
        Setmeal setmeal = Setmeal.builder()
                .id(id)
                .status(status)
                .build();
        setmealMapper.updateById(setmeal);
    }

    @Override
    public SetmealVO findById(Long id) {
        // 查询套餐数据
        SetmealVO setmealVO = setmealMapper.getSetmealById(id);

        // 查询套餐对应的菜品数据
        List<SetmealDish> setmealDishes = setmealDishMapper.getBySetMealId(id);

        // 封装数据并返回
        setmealVO.setSetmealDishes(setmealDishes);
        log.info("查询套餐：{}", setmealVO);
        return setmealVO;
    }

    /**
     * 修改套餐
     * @param sDTO
     */
    @Transactional
    @Override
    public void editSetmeal(SetmealDTO sDTO) {
        //修改套餐数据
        Setmeal setmeal = new Setmeal();
        BeanUtils.copyProperties(sDTO, setmeal);
        setmealMapper.updateById(setmeal);
        //修改套餐菜品关系数据
        setmealDishMapper.delete(new LambdaQueryWrapper<SetmealDish>().eq(SetmealDish::getSetmealId, sDTO.getId()));
        List<SetmealDish> setmealDishes = sDTO.getSetmealDishes();
        if (!CollectionUtils.isEmpty(setmealDishes)){
            setmealDishes.forEach(setmealDish -> setmealDish.setSetmealId(sDTO.getId()));
            setmealDishMapper.insert(setmealDishes);
        }
    }

/*    @Override
    public List<SetmealVO> getDishById(Long id) {
        return setmealMapper.selectBySetmealId(id);
    }*/
    /**
     * 根据id查询套餐数据
     * @return
     */
    @Override
    public List<Setmeal> listByCondition(Setmeal setmeal) {
        //根据分类id和套餐状态查询
        List<Setmeal> setmeals = setmealMapper.selectList(new LambdaQueryWrapper<Setmeal>().eq(Setmeal::getCategoryId, setmeal.getCategoryId())
                .eq(Setmeal::getStatus, setmeal.getStatus()));
        return setmeals;
    }


    @Override
    public List<DishItemVO> getDishItemById(Long id) {
        //1.查询redis数据
        Object o = redisTemplate.opsForValue().get(RedisConstant.SETMEAL_KRY + id);
        if (o != null){
            return (List<DishItemVO>) o;
        }
       /* //根据套餐id查询套餐下的菜品数据
        List<SetmealDish> setmealDishes = setmealDishMapper.selectList(new LambdaQueryWrapper<SetmealDish>().eq(SetmealDish::getSetmealId, id));
        if (!CollectionUtils.isEmpty(setmealDishes)){
            return Collections.emptyList();
        }
//        List<Long> dishIds = setmealDishes.stream().map(SetmealDish::getDishId).collect(Collectors.toList());
        setmealDishes.stream().map(setmealDish -> {
            DishItemVO dishItemVO = new DishItemVO();
            dishItemVO.setCopies(setmealDish.getCopies());
            dishItemVO.setName(setmealDish.getName());
            //根据菜品id查询菜品
            Dish dish = dishMapper.selectById(setmealDish.getDishId());
            dishItemVO.setImage(dish.getImage());
            dishItemVO.setDescription(dish.getDescription());
            return dishItemVO;
        });
*/
        List<DishItemVO> result = setmealMapper.getDishItemBySetmealId(id);
        //2.将数据存入redis
        redisTemplate.opsForValue().set(RedisConstant.SETMEAL_KRY + id, result);
        return result;
    }
}